//
//  RecordHelper.m
//  Learn
//
//  Created by chijianguo on 2024/4/14.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "RecordHelper.h"
#import <AVFoundation/AVFoundation.h>
@interface RecordHelper()
 
@property (nonatomic , strong) AVAudioSession *session;
@property (nonatomic , strong) AVAudioRecorder *recorder;
@property (nonatomic , strong) NSURL *recordFileUrl;
 
 
@end
 
@implementation RecordHelper
 
- (void)startRecord:(NSString *)path{
    [self session];
    
    //获取文件路径
    self.recordFileUrl = [NSURL fileURLWithPath:[[path stringByDeletingPathExtension] stringByAppendingString:@".pcm"]];
    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: 16000.0],AVSampleRateKey,
                                   // 音频格式
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
    [_recorder recordForDuration:600];
    if (_recorder) {
        if ([_recorder isRecording]) {
            NSLog(@"dssdsdsd");
        }
        _recorder.meteringEnabled = YES;
        [_recorder prepareToRecord];
        [_recorder record];
        
    }else{
        NSLog(@"音频格式和文件存储格式不匹配,无法初始化Recorder");
        
    }
}
- (void)stopRecord{
    
    if ([self.recorder isRecording]) {
        [self.recorder stop];
        _recorder = nil;
    }
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:[self.recordFileUrl path]]){
        NSLog(@"录音成功");
    }else{
        NSLog(@"录音失败");
    }
 
}
 
- (AVAudioSession *)session{
    if(!_session){
        _session = [AVAudioSession sharedInstance];
    }
    NSError *sessionError;
    [_session setCategory:AVAudioSessionCategoryRecord error:&sessionError];
    
    if (_session == nil) {
        NSLog(@"Error creating session: %@",[sessionError description]);
    }else{
        [_session setActive:YES error:nil];
    }
    return _session;
}
 
 
@end
